package demo1;
import java.io.*;
import java.net.*;
public class fuwuqi {
        public static void main(String[] args) {
            try {
                ServerSocket serverSocket = new ServerSocket(8081);
                System.out.println("服务器启动，等待客户端连接...");

                // 接收客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接");

                // 创建输入流，用于读取客户端发送的消息
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                // 创建输出流，用于向客户端发送消息
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                // 创建线程，用于接收客户端消息
                new Thread(() -> {
                    try {
                        String message;
                        while ((message = in.readLine()) != null) {
                            System.out.println("客户端说：" + message);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();

                // 创建线程，用于读取控制台输入并发送到客户端
                new Thread(() -> {
                    try {
                        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
                        String message;
                        while ((message = console.readLine()) != null) {
                            out.write(message + "\n");
                            out.flush();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

